package com.heer.gymnasium.fragment;

import android.Manifest;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.heer.api.ResponseData.ApiResponse;
import com.heer.api.callback.BaseCallback;
import com.heer.api.constants.IConstants;
import com.heer.api.sign.SDKRuntimeException;
import com.heer.api.sign.SignHelper;
import com.heer.gymnasium.R;
import com.heer.gymnasium.activity.InvitationCardActivity;
import com.heer.gymnasium.activity.LoginActivity;
import com.heer.gymnasium.activity.MyCardActivity;
import com.heer.gymnasium.activity.MyMessageActivity;
import com.heer.gymnasium.activity.MyWalletActivity;
import com.heer.gymnasium.activity.ResetPassWordActivity;
import com.heer.gymnasium.activity.SettledInActivity;
import com.heer.gymnasium.activity.UserCenterActivity;
import com.heer.gymnasium.adapter.MineFragmentActionAdapter;
import com.heer.gymnasium.constant.Extras;
import com.heer.gymnasium.constant.Type;
import com.heer.gymnasium.event.BaseEvent;
import com.heer.gymnasium.permission.AppSettingsDialog;
import com.heer.gymnasium.permission.EasyPermissions;
import com.heer.gymnasium.util.LoadImageUtil;
import com.heer.gymnasium.util.Session;
import com.heer.gymnasium.util.SystemUtils;
import com.heer.gymnasium.widget.GlideCircleImage;
import com.heer.gymnasium.widget.MyListView;
import com.heer.model.LoginBean;
import com.heer.model.MineActionBean;
import com.heer.model.UserAvatarBean;
import com.heer.model.UserInfoBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;

import static com.heer.gymnasium.constant.Constants.RC_VIDEO_AND_EXTENER;
import static com.heer.gymnasium.event.EventConstant.MINE_TO_ORDER;
import static com.heer.gymnasium.event.EventConstant.USER_CENTER_REFRESH;
import static com.heer.gymnasium.event.EventConstant.USER_NEW_MSG;

/**
 * Created by rzw2 on 2017/4/5.
 */

public class MainMineFragment extends BaseFragment implements EasyPermissions.PermissionCallbacks {
    @BindView(R.id.image_avatar)
    ImageView imageAvatar;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.btn_wallet)
    Button btnWallet;
    @BindView(R.id.btn_card)
    Button btnCard;
    @BindView(R.id.list)
    MyListView list;
    @BindView(R.id.btn_link)
    LinearLayout btnLink;
    @BindView(R.id.btn_login_out)
    Button btnLoginOut;
    @BindView(R.id.ll_mine_message)
    LinearLayout ll_message;
    @BindView(R.id.iv_mine_clue)
    ImageView iv_clue;

    private static final Integer[] ACTIONS = new Integer[]{Type.MINE_ACTION_INVITED, Type.MINE_ACTION_ORDER, Type.MINE_ACTION_RESET, Type.MINE_ACTION_CENTER, Type.MINE_ACTION_SETTLED_IN};
    private static final String[] TITLES = new String[]{"邀请函", "我的订单", "重置密码", "个人中心", "商家入驻"};

    private List<MineActionBean> mList = new ArrayList<>();
    private MineFragmentActionAdapter mAdapter;

    private UserInfoBean mData;

    @Override
    protected int setConvertView() {
        return R.layout.fragment_main_mine;
    }

    @Override
    protected void init() {
        super.init();

        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);

        for (int actionId : ACTIONS) {
            switch (actionId) {
                case Type.MINE_ACTION_INVITED:
                    mList.add(new MineActionBean(actionId, TITLES[actionId], false));
                    break;
                case Type.MINE_ACTION_CENTER:
                    mList.add(new MineActionBean(actionId, TITLES[actionId], false));
                    break;
                case Type.MINE_ACTION_ORDER:
                    mList.add(new MineActionBean(actionId, TITLES[actionId], false));
                    break;
                case Type.MINE_ACTION_RESET:
                    mList.add(new MineActionBean(actionId, TITLES[actionId], false));
                    break;
                case Type.MINE_ACTION_SETTLED_IN:
                    mList.add(new MineActionBean(actionId, TITLES[actionId], false));
                    break;
            }
        }
    }

    @Override
    protected void initView() {
        super.initView();
        list.setAdapter(mAdapter = new MineFragmentActionAdapter(mContext));
        mAdapter.setItems(mList);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MineActionBean item = mList.get(position);
                switch (item.getActionId()) {
                    case Type.MINE_ACTION_INVITED:
                        startActivity(new Intent(mContext, InvitationCardActivity.class));
                        break;
                    case Type.MINE_ACTION_CENTER:
                        if (mData != null) {
                            Intent intent = new Intent(mContext, UserCenterActivity.class);
                            intent.putExtra(Extras.EXTRA_DATA, mData);
                            startActivity(intent);
                        }else {
                            Intent intent = new Intent(mContext, LoginActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            mContext.startActivity(intent);
                        }
                        break;
                    case Type.MINE_ACTION_ORDER:
                        EventBus.getDefault().post(new BaseEvent(MINE_TO_ORDER, String.valueOf(1)));
                        break;
                    case Type.MINE_ACTION_RESET:
                        startActivity(new Intent(mContext, ResetPassWordActivity.class));
                        break;
                    case Type.MINE_ACTION_SETTLED_IN:
                        startActivity(new Intent(mContext, SettledInActivity.class));
                        break;
                }
            }
        });
    }

    @Override
    protected void loadData() {
        super.loadData();

        String[] perms = {Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(mContext, perms)) {
            mAppHelper.apiService().getUserInfo(Session.getUserId()).enqueue(new BaseCallback<ApiResponse<UserInfoBean>>() {
                @Override
                public void onResponse(Call<ApiResponse<UserInfoBean>> call, Response<ApiResponse<UserInfoBean>> response) {
                    super.onResponse(call, response);
                    if (response.isSuccessful() && response.body().isSccessful()) {
                        mData = response.body().getData();
                        try {
                            tvName.setText(URLDecoder.decode(response.body().getData().getUserInfo().getNickname(), "utf-8"));
                            Glide.with(mContext)
                                    .load(LoadImageUtil.getLoadImageUrl(URLDecoder.decode(response.body().getData().getUserInfo().getAvatar(), "utf-8")))
                                    .transform(new GlideCircleImage(mContext))
                                    .placeholder(R.mipmap.ic_default_avatar)
                                    .into(imageAvatar);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        Session.setUserName(response.body().getData().getUserInfo().getNickname());
                        Session.setUserPicUrl(response.body().getData().getUserInfo().getAvatar());
                    }
                    if (response.body().isTokenExpire()) {
                        toLogin();
                    }

                }

                @Override
                public void onFailure(Call<ApiResponse<UserInfoBean>> call, Throwable t) {
                    super.onFailure(call, t);
                }
            });
        } else {
            EasyPermissions.requestPermissions(this, "需要使用摄像头,读取手机状态,使用sd卡权限", RC_VIDEO_AND_EXTENER, perms);
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.image_avatar, R.id.btn_wallet, R.id.btn_card, R.id.btn_link, R.id.btn_login_out,R.id.ll_mine_message})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.image_avatar:
//                String[] perms = {Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
//                if (EasyPermissions.hasPermissions(mContext, perms)) {
//                    Intent intent = new Intent(mContext,
//                            PhotoWallSingleActivity.class);
//                    startActivityForResult(intent, 0);
//                }
                break;
            case R.id.btn_wallet:
                startActivity(new Intent(mContext, MyWalletActivity.class));
                break;
            case R.id.btn_card:
                startActivity(new Intent(mContext, MyCardActivity.class));
                break;
            case R.id.btn_link:
                SystemUtils.dial(mContext, "15902207999");
                break;
            case R.id.ll_mine_message:
                startActivity(new Intent(mContext, MyMessageActivity.class));
                iv_clue.setVisibility(View.GONE);
                break;
            case R.id.btn_login_out:
                mAppHelper.apiService().toLogout(Session.getUserId()).enqueue(new BaseCallback<ApiResponse<LoginBean>>() {
                    @Override
                    public void onResponse(Call<ApiResponse<LoginBean>> call, Response<ApiResponse<LoginBean>> response) {
                        super.onResponse(call, response);
                        Toast.makeText(mContext, "退出成功", Toast.LENGTH_SHORT).show();
                        Session.clearShareP();
                        startActivity(new Intent(mContext, LoginActivity.class));
                        getActivity().finish();
                    }

                    @Override
                    public void onFailure(Call<ApiResponse<LoginBean>> call, Throwable t) {
                        super.onFailure(call, t);
                        Toast.makeText(mContext, "退出成功", Toast.LENGTH_SHORT).show();
                        Session.clearShareP();
                        startActivity(new Intent(mContext, LoginActivity.class));
                        getActivity().finish();
                    }
                });
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 100) {
            int code = data.getIntExtra("code", -1);
            if (code != 100) {
                return;
            }
            List<String> list = data.getStringArrayListExtra("paths");
            if (null != list && list.size() > 0) {
                final String path = list.get(0);
                Log.e("zxw", "onActivityResult: " + path);
                File file = new File(path);
                RequestBody requestFile =
                        RequestBody.create(MediaType.parse("multipart/form-data"), file);

                MultipartBody.Part body = MultipartBody.Part.createFormData("pic", file.getName(), requestFile);

                SignHelper sign = new SignHelper("");


                try {
                    mAppHelper.apiService().avatarUpdate(RequestBody.create(MediaType.parse("text/plain"), IConstants.AVATAR_UPDATE)
                            , RequestBody.create(MediaType.parse("text/plain"), sign.GetParameter("key"))
                            , RequestBody.create(MediaType.parse("text/plain"), sign.GetParameter("unixtime"))
                            , RequestBody.create(MediaType.parse("text/plain"), sign.GetParameter("token"))
                            , RequestBody.create(MediaType.parse("text/plain"), sign.getSign())
                            , RequestBody.create(MediaType.parse("text/plain"), "jpg"), body).enqueue(new BaseCallback<ApiResponse<UserAvatarBean>>() {
                        @Override
                        public void onResponse(Call<ApiResponse<UserAvatarBean>> call, Response<ApiResponse<UserAvatarBean>> response) {
                            super.onResponse(call, response);
                            if (response.isSuccessful() && response.body().isSccessful()) {
                                Glide.with(mContext)
                                        .load(LoadImageUtil.getLoadImageUrl(response.body().getData().getAvatar()))
                                        .placeholder(R.mipmap.ic_default_avatar)
                                        .into(imageAvatar);
                                Session.setUserPicUrl(response.body().getData().getAvatar());
                            }
                        }

                        @Override
                        public void onFailure(Call<ApiResponse<UserAvatarBean>> call, Throwable t) {
                            super.onFailure(call, t);
                        }
                    });
                } catch (SDKRuntimeException e) {
                    e.printStackTrace();
                }
//
//                Bitmap photo = ImageUtil.convertToBitmap(path);
//                ByteArrayOutputStream baos = null;
//                try {
//                    baos = new ByteArrayOutputStream();
//                    photo.compress(Bitmap.CompressFormat.JPEG, 95, baos);
//                    int options = 95;
//                    while (baos.toByteArray().length / 1024 > 150) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
//                        options -= 10;// 每次都减少10
//                        baos.reset();// 重置baos即清空baos
//                        photo.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
//                    }
//
//                    RequestBody requestBody1 =
//                            RequestBody.create(MediaType.parse("multipart/form-data"), new File(path));
//
//                    mAppHelper.apiService().avatarUpdate(".png", baos.toByteArray()).enqueue(new BaseCallback<ApiResponse<UserAvatarBean>>() {
//                        @Override
//                        public void onResponse(Call<ApiResponse<UserAvatarBean>> call, Response<ApiResponse<UserAvatarBean>> response) {
//                            super.onResponse(call, response);
//                            if (response.isSuccessful() && response.body().isSccessful()) {
//                                Glide.with(mContext)
//                                        .load(LoadImageUtil.getLoadImageUrl(response.body().getData().getAvatar()))
//                                        .placeholder(R.mipmap.ic_default_avatar)
//                                        .into(imageAvatar);
//                                Session.setUserPicUrl(response.body().getData().getAvatar());
//                            }
//                        }
//
//                        @Override
//                        public void onFailure(Call<ApiResponse<UserAvatarBean>> call, Throwable t) {
//                            super.onFailure(call, t);
//                        }
//                    });
//                } catch (Exception e) {
//                    e.getStackTrace();
//                } finally {
//                    if (baos != null) {
//                        try {
//                            baos.close();
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
            }
        }
    }

    @Subscribe
    public void eventBus(BaseEvent event) {
        if (TextUtils.equals(event.getId(), USER_CENTER_REFRESH)) {
            loadData();
        }
        if(TextUtils.equals(event.getId(), USER_NEW_MSG)){
            iv_clue.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(mContext, perms)) {
            new AppSettingsDialog.Builder(this, "巫师运动要使用摄像头,读取手机状态,使用sd卡和录音权限，否则app可能无法正常运行")
                    .setPositiveButton(getString(R.string.setting))
                    .setNegativeButton(getString(R.string.cancel), null /* click listener */)
                    .setRequestCode(RC_VIDEO_AND_EXTENER)
                    .build()
                    .show();
        }
    }

}
